import 'dart:async';
import 'dart:math';

import 'package:audioplayers/audioplayers.dart' hide AudioPlayer;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logger/logger.dart';

import '../../../utils/audio_player_manager.dart';
import '../intent/game_state.dart';

class GameViewModel extends StateNotifier<GameState> {
  /// 音频播放器实例，用于播放各种游戏音效
  final random = Random();
  final audioManager = AudioPlayerManager();

  var logger = Logger(printer: PrefixPrinter(PrettyPrinter(colors: false)));

  /// 音频缓存实例，用于预加载和管理音频资源
  final audioCache = AudioCache(prefix: 'assets/audio/');

  // 缓存列表数据，避免重复创建
  late final List<RunBean> _runListCache;
  late final List<String> _numberListCache;
  late final List<BetBean> _buttonListCache;
  late final List<BetBean> _consoleListCache;
  late final List<int> _betListCache;

  GameViewModel() : super(GameState()) {
    // 初始化缓存数据
    _runListCache = _createRunList();
    _numberListCache = _createNumberList();
    _buttonListCache = _createButtonList();
    _consoleListCache = _createConsoleList();
    _betListCache = _createBetList();

    // 在构造函数中立即初始化数据
    initData();
  }

  String _createWinMusic() {
    final List<String> _runListCache = ['assets/audio/C01.mp3', 'assets/audio/C02.mp3', 'assets/audio/C03.mp3', 'assets/audio/C04.mp3', 'assets/audio/C05.mp3', 'assets/audio/C06.mp3', 'assets/audio/C07.mp3', 'assets/audio/C08.mp3', 'assets/audio/C09.mp3', 'assets/audio/C10.mp3', 'assets/audio/C11.mp3', 'assets/audio/C12.mp3', 'assets/audio/C13.mp3', 'assets/audio/C14.mp3', 'assets/audio/C15.mp3'];
    final random = Random();
    return _runListCache[random.nextInt(_runListCache.length)];
  }

  List<RunBean> _createRunList() {
    return [
      RunBean(name: '桔子', position: 0, imgRes: 'assets/images/run_orange.png', tag: 0, price: 10, left: _getLeft(0), top: _getTop(0)),
      RunBean(name: '铃铛', position: 1, imgRes: 'assets/images/run_bell.png', tag: 1, price: 10, left: _getLeft(1), top: _getTop(0)),
      RunBean(name: 'bar', position: 2, imgRes: 'assets/images/run_bar_50.png', tag: 2, price: 50, left: _getLeft(2), top: _getTop(0)),
      RunBean(name: 'bar', position: 3, imgRes: 'assets/images/run_bar_100.png', tag: 3, price: 100, left: _getLeft(3), top: _getTop(0)),
      RunBean(name: '苹果', position: 4, imgRes: 'assets/images/run_apple.png', tag: 4, price: 5, left: _getLeft(4), top: _getTop(0)),
      RunBean(name: '苹果', position: 5, imgRes: 'assets/images/run_apple_small.png', tag: 5, price: 3, left: _getLeft(5), top: _getTop(0)),
      RunBean(name: '芒果', position: 6, imgRes: 'assets/images/run_mango.png', tag: 6, price: 10, left: _getLeft(6), top: _getTop(0)),
      RunBean(name: '西瓜', position: 7, imgRes: 'assets/images/run_tsama.png', tag: 7, price: 20, left: _getLeft(6), top: _getTop(1)),
      RunBean(name: '西瓜', position: 8, imgRes: 'assets/images/run_tsama_small.png', tag: 8, price: 3, left: _getLeft(6), top: _getTop(2)),
      RunBean(name: '', position: 9, imgRes: 'assets/images/run_luck_blue.png', tag: 9, price: 0, left: _getLeft(6), top: _getTop(3)),
      RunBean(name: '苹果', position: 10, imgRes: 'assets/images/run_apple.png', tag: 4, price: 5, left: _getLeft(6), top: _getTop(4)),
      RunBean(name: '桔子', position: 11, imgRes: 'assets/images/run_orange_small.png', tag: 10, price: 3, left: _getLeft(6), top: _getTop(5)),
      RunBean(name: '桔子', position: 12, imgRes: 'assets/images/run_orange.png', tag: 0, price: 10, left: _getLeft(6), top: _getTop(6)),
      RunBean(name: '铃铛', position: 13, imgRes: 'assets/images/run_bell.png', tag: 1, price: 10, left: _getLeft(5), top: _getTop(6)),
      RunBean(name: '77', position: 14, imgRes: 'assets/images/run_seven_small.png', tag: 11, price: 3, left: _getLeft(4), top: _getTop(6)),
      RunBean(name: '77', position: 15, imgRes: 'assets/images/run_seven.png', tag: 12, price: 20, left: _getLeft(3), top: _getTop(6)),
      RunBean(name: '苹果', position: 16, imgRes: 'assets/images/run_apple.png', tag: 4, price: 5, left: _getLeft(2), top: _getTop(6)),
      RunBean(name: '芒果', position: 17, imgRes: 'assets/images/run_mango_small.png', tag: 13, price: 3, left: _getLeft(1), top: _getTop(6)),
      RunBean(name: '芒果', position: 18, imgRes: 'assets/images/run_mango.png', tag: 6, price: 10, left: _getLeft(0), top: _getTop(6)),
      RunBean(name: '双星', position: 19, imgRes: 'assets/images/run_star.png', tag: 14, price: 20, left: _getLeft(0), top: _getTop(5)),
      RunBean(name: '双星', position: 20, imgRes: 'assets/images/run_star_small.png', tag: 15, price: 3, left: _getLeft(0), top: _getTop(4)),
      RunBean(name: '', position: 21, imgRes: 'assets/images/run_luck_yellow.png', tag: 16, price: 0, left: _getLeft(0), top: _getTop(3)),
      RunBean(name: '苹果', position: 22, imgRes: 'assets/images/run_apple.png', tag: 4, price: 5, left: _getLeft(0), top: _getTop(2)),
      RunBean(name: '铃铛', position: 23, imgRes: 'assets/images/run_bell_small.png', tag: 17, price: 3, left: _getLeft(0), top: _getTop(1)),
    ];
  }

  List<RunBean> _getRunList() => _runListCache;

  List<String> _createNumberList() {
    List<String> numberList = [];
    numberList.add('assets/images/top_0.png');
    numberList.add('assets/images/top_1.png');
    numberList.add('assets/images/top_2.png');
    numberList.add('assets/images/top_3.png');
    numberList.add('assets/images/top_4.png');
    numberList.add('assets/images/top_5.png');
    numberList.add('assets/images/top_6.png');
    numberList.add('assets/images/top_7.png');
    numberList.add('assets/images/top_8.png');
    numberList.add('assets/images/top_9.png');
    return numberList;
  }

  List<String> _getNumberList() => _numberListCache;

  List<BetBean> _createButtonList() {
    List<BetBean> buttonList = [];
    buttonList.add(BetBean(name: 'bar', normalImage: 'assets/images/button_bar_normal.png', pressedImage: 'assets/images/button_bar_pressed.png', disabledImage: 'assets/images/button_bar_disabled.png', enabled: true, width: 55));
    buttonList.add(BetBean(name: '77', normalImage: 'assets/images/button_seven_normal.png', pressedImage: 'assets/images/button_seven_pressed.png', disabledImage: 'assets/images/button_seven_disabled.png', enabled: true, width: 55));
    buttonList.add(BetBean(name: '双星', normalImage: 'assets/images/button_star_normal.png', pressedImage: 'assets/images/button_star_pressed.png', disabledImage: 'assets/images/button_star_disabled.png', enabled: true, width: 55));
    buttonList.add(BetBean(name: '西瓜', normalImage: 'assets/images/button_tsama_normal.png', pressedImage: 'assets/images/button_tsama_pressed.png', disabledImage: 'assets/images/button_tsama_disabled.png', enabled: true, width: 55));
    buttonList.add(BetBean(name: '铃铛', normalImage: 'assets/images/button_bell_normal.png', pressedImage: 'assets/images/button_bell_pressed.png', disabledImage: 'assets/images/button_bell_disabled.png', enabled: true, width: 55));
    buttonList.add(BetBean(name: '芒果', normalImage: 'assets/images/button_mango_normal.png', pressedImage: 'assets/images/button_mango_pressed.png', disabledImage: 'assets/images/button_mango_disabled.png', enabled: true, width: 55));
    buttonList.add(BetBean(name: '桔子', normalImage: 'assets/images/button_orange_normal.png', pressedImage: 'assets/images/button_orange_pressed.png', disabledImage: 'assets/images/button_orange_disabled.png', enabled: true, width: 55));
    buttonList.add(BetBean(name: '苹果', normalImage: 'assets/images/button_apple_normal.png', pressedImage: 'assets/images/button_apple_pressed.png', disabledImage: 'assets/images/button_apple_disabled.png', enabled: true, width: 55));
    return buttonList;
  }

  List<BetBean> _getButtonList() => _buttonListCache;

  List<BetBean> _createConsoleList() {
    List<BetBean> consoleList = [];
    consoleList.add(BetBean(name: '左', normalImage: 'assets/images/console_left_normal.png', pressedImage: 'assets/images/console_left_pressed.png', disabledImage: 'assets/images/console_left_disabled.png', enabled: true, width: 74));
    consoleList.add(BetBean(name: '右', normalImage: 'assets/images/console_right_normal.png', pressedImage: 'assets/images/console_right_pressed.png', disabledImage: 'assets/images/console_right_disabled.png', enabled: true, width: 68));
    consoleList.add(BetBean(name: '小', normalImage: 'assets/images/console_small_normal.png', pressedImage: 'assets/images/console_small_pressed.png', disabledImage: 'assets/images/console_small_disabled.png', enabled: true, width: 59));
    consoleList.add(BetBean(name: '大', normalImage: 'assets/images/console_big_normal.png', pressedImage: 'assets/images/console_big_pressed.png', disabledImage: 'assets/images/console_big_disabled.png', enabled: true, width: 59));
    consoleList.add(BetBean(name: 'GO', normalImage: 'assets/images/console_go_normal.png', pressedImage: 'assets/images/console_go_pressed.png', disabledImage: 'assets/images/console_go_disabled.png', enabled: true, width: 110));
    return consoleList;
  }

  List<BetBean> _getConsoleList() => _consoleListCache;

  List<int> _createBetList() {
    List<int> betList = [];
    betList.add(0);
    betList.add(0);
    betList.add(0);
    betList.add(0);
    betList.add(0);
    betList.add(0);
    betList.add(0);
    betList.add(0);
    return betList;
  }

  List<int> _getBetList() => _betListCache;

  void initData() {
    state = state.copyWith(runList: []);
    state = state.copyWith(numberList: _getNumberList());
    state = state.copyWith(betList: _getBetList());
    List<BetBean> mButtonList = _getButtonList();
    List<BetBean> mConsoleList = _getConsoleList();
    state = state.copyWith(buttonList: mButtonList);
    state = state.copyWith(consoleList: mConsoleList);
    state = state.copyWith(sizeNumber: 0);
  }

  double _getLeft(int position) {
    return position * (347.0 / 6) + 30;
  }

  double _getTop(int position) {
    return position * (346.0 / 6) + 136;
  }

  void clickButton(BuildContext context, int index) async {
    logger.e('点击了  ${state.betList[index]}');
    //检查当前积分是否为空如果为空则提示用户充值
    if (state.credit <= 0 && state.bonusWin <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请先充值!")));
      return;
    }
    // 防止重复点击
    if (!isClick) {
      return;
    }
    if (state.bonusWin > 0) {
      return;
    }
    final currentBetList = List<int>.from(state.betList);
    if (index < 0 || index >= currentBetList.length) {
      return;
    }
    if (currentBetList[index] >= 99) {
      return;
    }
    if (state.credit > 1) {
      audioManager.setAudioList(['assets/audio/ding.mp3']);
      currentBetList[index] = currentBetList[index] + 1;
      state = state.copyWith(betList: currentBetList, credit: state.credit - 1);
      // 使用copyWith更新嵌套状态，确保UI正确更新
      if (!state.consoleList[state.consoleList.length - 1].enabled) {
        final updatedConsoleList = List<BetBean>.from(state.consoleList);
        updatedConsoleList[updatedConsoleList.length - 1] = updatedConsoleList[updatedConsoleList.length - 1].copyWith(enabled: true);
        state = state.copyWith(consoleList: updatedConsoleList);
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("无积分")));
    }
  }

  String getResForNumberStart(int number) {
    String str = number.abs().toString();
    // 修复个位数处理逻辑
    int index = str.length > 1 ? int.parse(str[0]) : int.parse(str);
    return state.numberList[index];
  }

  String getResForNumberEnd(int number) {
    return state.numberList[number.abs() % 10];
  }

  int adfasf = 0;

  clickLeftButton(BuildContext context) {
    logger.e("clickLeftButton");
    if (state.credit <= 0 && state.bonusWin <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请先充值!")));
      return;
    }
    if (!isClick) {
      return;
    }
    if (state.bonusWin <= 0) {
      return;
    }
    if (state.bonusWin < state.tempBonusWin * 2) {
      audioManager.setAudioList(['assets/audio/ding.mp3']);
      int finalLeftTotal = state.tempBonusWin + state.tempBonusWin;
      int finalRightTotal = state.bonusWin + state.credit;
      if (finalLeftTotal < finalRightTotal) {
        state = state.copyWith(bonusWin: finalLeftTotal, credit: finalRightTotal - finalLeftTotal);
      } else {
        state = state.copyWith(bonusWin: finalRightTotal, credit: 0);
      }
    }
  }

  void clickRightButton(BuildContext context) {
    logger.e("clickRightButton");
    //检查当前积分是否为空如果为空则提示用户充值
    if (state.credit <= 0 && state.bonusWin <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请先充值!")));
      return;
    }
    if (!isClick) {
      return;
    }
    if (state.bonusWin <= 0) {
      return;
    }
    audioManager.setAudioList(['assets/audio/ding.mp3']);
    if (state.bonusWin - 1 >= 0) {
      state = state.copyWith(bonusWin: state.bonusWin - 1, credit: state.credit + 1);
      if (state.bonusWin == 0) {
        state = state.copyWith(lastBetList: state.betList, betList: _getBetList());
      }
    }
  }

  Future<void> clickLongRightButton(BuildContext context) async {
    logger.e("clickLongRightButton");
    if (!isClick) {
      return;
    }
    if (state.bonusWin <= 0) {
      return;
    }
    int temp = state.bonusWin;
    for (int i = 0; i < temp; i++) {
      state = state.copyWith(bonusWin: state.bonusWin - 1, credit: state.credit + 1);
      await Future.delayed(Duration(milliseconds: 100));
    }

    // state = state.copyWith(lastBetList: state.betList, betList: _getBetList());

    // //检查当前积分是否为空如果为空则提示用户充值
    // if (state.credit <= 0 && state.bonusWin <= 0) {
    //   ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请先充值!")));
    //   return;
    // }
    // if (!isClick) {
    //   return;
    // }
    // if (state.bonusWin <= 0) {
    //   return;
    // }
    // if (state.bonusWin - 1 >= 0) {
    //   state = state.copyWith(bonusWin: state.bonusWin - 1, credit: state.credit + 1);
    // }
  }

  // Future<void> clickSmallButton(BuildContext context) async {
  //   logger.e("clickSmallButton");
  //   int temp = random.nextInt(13) + 26;
  //   List<String> hitAudioList = List.filled(temp, 'assets/audio/hit.mp3');
  //   audioManager.setAudioList(hitAudioList);
  //   logger.e("clickRightButton   ${temp}");
  //   for (int i = 0; i < temp; i++) {
  //     state = state.copyWith(sizeNumber: i % 13 + 1);
  //     await Future.delayed(Duration(milliseconds: 81));
  //   }
  // }

  Future<void> clickSmallButton(BuildContext context) async {
    logger.e("clickSmallButton");
    //检查当前积分是否为空如果为空则提示用户充值
    if (state.credit <= 0 && state.bonusWin <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请先充值!")));
      return;
    }
    if (!isClick) {
      return;
    }
    if (state.bonusWin <= 0) {
      return;
    }
    isClick = false;
    int temp = random.nextInt(13) + 13;
    List<String> hitAudioList = List.filled(temp, 'assets/audio/hit.mp3');
    audioManager.setAudioList(hitAudioList);
    for (int i = 0; i < hitAudioList.length; i++) {
      state = state.copyWith(sizeNumber: i % 13 + 1);
      await Future.delayed(Duration(milliseconds: 81));
    }
    //如果中了，播放中将音乐
    if (state.sizeNumber < 7) {
      print('中奖了');
      audioManager.setAudioList(['assets/audio/luklySuccess.mp3', _createWinMusic()]);
      state = state.copyWith(bonusWin: state.bonusWin * 2, tempBonusWin: state.bonusWin * 2);
    } else if (state.sizeNumber == 7) {
      print('平');
    } else {
      print('没中奖');
      audioManager.setAudioList(['assets/audio/luklyFail.mp3']);
      state = state.copyWith(bonusWin: 0, tempBonusWin: 0);
    }
    isClick = true;
  }

  Future<void> clickBigButton(BuildContext context) async {
    logger.e("clickBigButton");
    //检查当前积分是否为空如果为空则提示用户充值
    if (state.credit <= 0 && state.bonusWin <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请先充值!")));
      return;
    }
    if (!isClick) {
      return;
    }
    if (state.bonusWin <= 0) {
      return;
    }
    isClick = false;
    int temp = random.nextInt(13) + 13;
    List<String> hitAudioList = List.filled(temp, 'assets/audio/hit.mp3');
    audioManager.setAudioList(hitAudioList);
    for (int i = 0; i < hitAudioList.length; i++) {
      state = state.copyWith(sizeNumber: i % 13 + 1);
      await Future.delayed(Duration(milliseconds: 81));
    }
    if (state.sizeNumber < 7) {
      print('没中奖');
      audioManager.setAudioList(['assets/audio/luklyFail.mp3']);
      state = state.copyWith(bonusWin: 0, tempBonusWin: 0);
    } else if (state.sizeNumber == 7) {
      print('平');
    } else {
      print('中奖了');
      audioManager.setAudioList(['assets/audio/luklySuccess.mp3', _createWinMusic()]);
      state = state.copyWith(bonusWin: state.bonusWin * 2, tempBonusWin: state.bonusWin * 2);
    }
    isClick = true;
  }

  /// 变速控制器，用于控制老虎机旋转速度的变化

  /// 当前步数，记录老虎机旋转的当前位置
  int currentStep = 0;

  /// 总步数，记录老虎机本次旋转的总步数
  int totalStep = 0;

  /// 是否可以点击，防止重复点击的标志位
  bool isClick = true;

  DateTime startTime = DateTime.now();

  /// GO按钮的点击事件
  ///
  /// 处理用户点击GO按钮的完整流程：
  /// 1. 停止当前音频播放并播放旋转音效
  /// 2. 检查用户是否已下注
  /// 3. 初始化旋转参数并开始旋转动画
  Future<void> clickGoButton(BuildContext context) async {
    logger.e("用户点击了GO按钮");
    //检查当前积分是否为空如果为空则提示用户充值
    if (state.credit <= 0 && state.bonusWin <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请先充值!")));
      return;
    }
    // 检查用户是否已下注
    int totalBet = state.betList.fold(0, (sum, bet) => sum + bet);
    // 如果未下注，提示用户先下注
    if (totalBet == 0) {
      //如果上次压住金额是空则提示用户请先压住
      int lastBetTotal = state.lastBetList.fold(0, (sum, bet) => sum + bet);
      if (lastBetTotal == 0) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请先押注!")));
        return;
      } else {
        state = state.copyWith(betList: state.lastBetList, credit: state.credit - lastBetTotal);
      }
    }
    // 防止重复点击
    if (!isClick) {
      return;
    }
    //把左侧赢的彩金移动到右侧
    if (state.bonusWin > 0) {
      isClick = false;
      audioManager.setAudioList(['assets/audio/hitLukly.mp3']);
      // 逐步减少bonusWin并增加credit
      int currentBonusWin = state.bonusWin;
      int currentCredit = state.credit;
      // 计算需要执行的步数
      const totalDuration = Duration(milliseconds: 888);
      int stepCount = state.bonusWin;
      final stepDuration = Duration(milliseconds: totalDuration.inMilliseconds ~/ stepCount);
      state = state.copyWith(lastBetList: state.betList, betList: _getBetList());
      // 逐步更新状态
      for (int i = 0; i < stepCount; i++) {
        if (currentBonusWin > 0) {
          currentBonusWin--;
          currentCredit++;
          state = state.copyWith(bonusWin: currentBonusWin, credit: currentCredit);
        }
        await Future.delayed(stepDuration);
      }
      isClick = true;
      return;
    }
    logger.e("开始旋转");
    isClick = false;
    //获取最终位置
    totalStep = random.nextInt(24) + 96; // 随机生成总步数(96-119)
    int nextIndex = (totalStep + state.lastIndex) % 24;
    RunBean mRunBean = _getRunList()[nextIndex];
    bool hasWon = false;
    int winPrice = 0;
    for (int i = 0; i < state.betList.length; i++) {
      if (state.betList[i] > 0) {
        if (_getButtonList()[i].name == mRunBean.name) {
          winPrice = mRunBean.price * state.betList[i];
          hasWon = true;
        }
      }
    }
    if (hasWon) {
      audioManager.setAudioList(['assets/audio/rotate_start.mp3', 'assets/audio/rotating.mp3', 'assets/audio/rotate_end.mp3', 'assets/audio/ding.mp3', getSoundForName(mRunBean.name), _createWinMusic()]);
    } else {
      audioManager.setAudioList(['assets/audio/rotate_start.mp3', 'assets/audio/rotating.mp3', 'assets/audio/rotate_end.mp3', 'assets/audio/ding.mp3']);
    }

    // 使用变速控制器实现加速→匀速→减速
    final speedController = VariableSpeedController(totalStep: totalStep, totalDuration: Duration(milliseconds: 3500), accelerateSteps: 24);

    for (int i = 0; i < totalStep; i++) {
      // 计算当前步的延迟时间
      Duration delay = speedController.getDelay(i);
      int tempNextIndex = (i + state.lastIndex + 1) % 24;
      List<RunBean> tempList = [];
      tempList.add(_getRunList()[tempNextIndex]);
      await Future.delayed(delay);
      state = state.copyWith(runList: tempList);
    }
    logger.e('上次位置：${state.lastIndex} 需要移动${totalStep}步 也就是往前移动${(totalStep) % 24}步');
    isClick = true;
    state = state.copyWith(lastIndex: nextIndex);
    if (winPrice <= 0) {
      var ssssssss = state.betList;
      state = state.copyWith(bonusWin: winPrice, tempBonusWin: winPrice, lastBetList: ssssssss, betList: _getBetList());
    } else {
      state = state.copyWith(bonusWin: winPrice, tempBonusWin: winPrice);
    }
  }

  //根据名字获取播放的声音
  String getSoundForName(String name) {
    switch (name) {
      case '苹果':
        return 'assets/audio/Y101.mp3';
      case '桔子':
        return 'assets/audio/Y102.mp3';
      case '芒果':
        return 'assets/audio/Y103.mp3';
      case '铃铛':
        return 'assets/audio/Y104.mp3';
      case '西瓜':
        return 'assets/audio/Y105.mp3';
      case '双星':
        return 'assets/audio/Y106.mp3';
      case '77':
        return 'assets/audio/Y107.mp3';
      case 'bar':
        return 'assets/audio/Y108.mp3';
      case '大三元':
        return 'assets/audio/Y114.mp3';
      case '小三元':
        return 'assets/audio/Y115.mp3';
      case '大四喜':
        return 'assets/audio/Y117.mp3';
      case '纵横四海':
        return 'assets/audio/Y118.mp3';
      case '大满贯':
        return 'assets/audio/Y120.mp3';
      case '天女散花':
        return 'assets/audio/Y122.mp3';
      case '开火车':
        return 'assets/audio/Y124.mp3';
      case '送灯':
        return 'assets/audio/Y131.mp3';
      case '真可惜啊':
        return 'assets/audio/zhenkexi.mp3';
      case '中了':
        return 'assets/audio/zhongle.mp3';
      default:
        return 'assets/audio/end.mp3';
    }
  }

  // 添加dispose方法以正确释放资源
  Future<void> dispose() async {
    await audioManager.dispose();
    super.dispose();
  }
}

/// 变速控制器类
///
/// 控制老虎机旋转的不同阶段的速度变化
/// 包括启动阶段的减速、中间阶段的匀速和结束阶段的减速
/// 变速控制器类
///
/// 控制老虎机旋转的不同阶段的速度变化
/// 包括启动阶段的加速、中间阶段的匀速和结束阶段的减速
/// 变速控制器类
///
/// 确保在指定总时长内完成所有步数，实现加速→匀速→减速的速度变化
class VariableSpeedController {
  final int totalStep;
  final Duration totalDuration;
  final int accelerateSteps;
  late final int constantSteps;
  final int fastDelay; // 最快速度(毫秒)
  final int maxDelay; // 最慢速度(毫秒)

  late final List<int> _delays;

  VariableSpeedController({
    required this.totalStep,
    required this.totalDuration,
    this.accelerateSteps = 24,
    this.fastDelay = 10,
    this.maxDelay = 120, // 缩短最大延迟时间
  }) {
    constantSteps = totalStep - (accelerateSteps * 2);
    if (constantSteps < 0) {
      constantSteps = 0;
    }
    _generateDelays();
  }

  /// 生成延迟时间序列，确保总和为总时长
  void _generateDelays() {
    _delays = [];

    // 计算加速阶段总时间（前24步）
    double totalAccelerateTime = totalDuration.inMilliseconds * 0.3;

    // 计算减速阶段总时间（后24步）
    double totalDecelerateTime = totalDuration.inMilliseconds * 0.3;

    // 计算匀速阶段总时间
    double totalConstantTime = totalDuration.inMilliseconds - totalAccelerateTime - totalDecelerateTime;

    // 生成加速阶段延迟时间（从慢到快）
    // 使用5次方曲线，使加速过程在后面阶段急剧加速
    for (int i = 0; i < accelerateSteps; i++) {
      double t = i / accelerateSteps; // 0到1
      double easedT = t * t * t * t * t; // 5次方 - 加速效果更明显
      int delay = (maxDelay - (maxDelay - fastDelay) * easedT).round();
      _delays.add(delay);
    }

    // 调整加速阶段总和
    double actualAccelerateSum = _delays.fold<double>(0, (sum, d) => sum + d);
    double ratio1 = totalAccelerateTime / actualAccelerateSum;
    for (int i = 0; i < accelerateSteps; i++) {
      _delays[i] = (_delays[i] * ratio1).round();
    }

    // 生成匀速阶段延迟时间
    int constantDelay = constantSteps > 0 ? (totalConstantTime / constantSteps).round() : fastDelay;
    for (int i = 0; i < constantSteps; i++) {
      _delays.add(constantDelay);
    }

    // 生成减速阶段延迟时间（从快到慢）
    // 使用9次方曲线，使减速过程极度集中在最后几秒
    for (int i = 0; i < accelerateSteps; i++) {
      double t = i / accelerateSteps; // 0到1
      double easedT = 1 - (1 - t) * (1 - t) * (1 - t) * (1 - t) * (1 - t) * (1 - t) * (1 - t) * (1 - t) * (1 - t); // 9次方 - 极急减速
      int delay = (fastDelay + (maxDelay - fastDelay) * easedT).round();
      _delays.add(delay);
    }

    // 调整减速阶段总和
    double decelerateSum = _delays.skip(accelerateSteps + constantSteps).fold<double>(0, (sum, d) => sum + d);
    double ratio2 = totalDecelerateTime / decelerateSum;
    for (int i = accelerateSteps + constantSteps; i < _delays.length; i++) {
      _delays[i] = (_delays[i] * ratio2).round();
    }

    // 确保步数匹配
    while (_delays.length < totalStep) {
      _delays.add(fastDelay);
    }
    if (_delays.length > totalStep) {
      _delays = _delays.take(totalStep).toList();
    }
  }

  Duration getDelay(int currentStep) {
    if (currentStep < 0 || currentStep >= totalStep) {
      return Duration(milliseconds: fastDelay);
    }
    return Duration(milliseconds: _delays[currentStep]);
  }
}
